'use strict';
const BaseController = require('./base');
const { addUserImage, userInfoRules, marryLikeRule } = require('../validator/user/index');
const moment = require("moment");

class UserController extends BaseController {

  /**
   * 获取用户匹配还好
   */
  async getMarrayLike() {
    const userId = await this.userId();
    const user = await this.ctx.model.User.findByPk(userId, {
      attributes: ['id', 'marry_like']
    });
    if (!user || !(user.marry_like && user.marry_like.length > 0)) {
      this.ctx.helper.commonErr("用户没有设置匹配爱好");
    }
    this.ctx.helper.success({bean: JSON.parse(user.marry_like)});
  }

  /**
   * 更新用户匹配爱好
   */
  async updateMarrayLike() {
    const data = this.ctx.request.body;
    const errors = this.app.validator.validate(marryLikeRule, data);
    errors && this.ctx.helper.commonErr('参数错误', { beans: errors });
    const userId = await this.userId();
    const user = await this.ctx.model.User.findByPk(userId, {
      attributes: ['id', 'marry_like']
    });
    if (!user) {
      this.ctx.helper.commonErr("用户不存在");
    }
    user.marry_like = JSON.stringify(data);
    user.save();
    this.ctx.helper.success();
  }


  /**
   * 支付成功返回用户信息
   * @return use_like => 可用超喜欢数量
   * @return day => 用户vip剩余天数
   */
  async order() {
    const userId = await this.userId();
    const user = await this.ctx.model.User.findByPk(userId, {
      attributes: ['id', 'use_like', 'vip', 'open_time', 'expire_time']
    });
    let day = 0;
    const now = moment().format("YYYY-MM-DD HH:mm:ss")
    if (user.vip && moment(user.expire_time) > moment(now)) {
      day = moment(user.expire_time).diff(moment(user.open_time), 'days');
    }
    user.dataValues.day = day;
    this.ctx.helper.success({bean: user});

  }

  /**
   * 获取用户资料
   */
  async userInfo() {
    const data = this.ctx.request.body;
    const errors = this.app.validator.validate(userInfoRules, data);
    errors && this.ctx.helper.commonErr('参数错误', { beans: errors });
    const users = await this.service.user.findUserInfo(data.userId);
    this.ctx.helper.success({beans: users});
  }


  /**
   * 邀请好友
   */
  async invite() {
      const userId = await this.userId();
      const vipDays = await this.service.user.getLastVipDays(userId);
      const friends = await this.service.inviteFriend.getFriends(userId);
      const unlockFriends = await this.service.inviteFriend.getUnlockFriend(userId);
      this.ctx.helper.success({beans: {
        unlockFriends,
        vipDays,
        unlockCount: 3 - unlockFriends.length,
        successCount: friends.count,
        friends: friends.rows
      }})
  }


  /**
   * 喜欢，无感，超喜欢用户
   */
  async like() {
    const type = this.ctx.params.type;
    const userId = await this.userId();
    const users = await this.service.userLike.findByType(userId, type);
    this.ctx.helper.success({beans: users});
  }

  /**
   * 推荐用户
   * 每天中午12点推21个
   */
  async recommend() {
    const userId = await this.userId();
    //匹配偏好
    const user = await this.ctx.model.User.findByPk(userId);
    if (!user) {
      this.ctx.helper.commonErr("用户不存在");
    }
    // 昨天被推荐过的
    const like = await this.service.userLike.getUserLike(userId);
    const marryLike = await this.marryLike(user)
    //推荐21条
    const users = await this.service.user.getRecommendUser(user, marryLike, like);

    this.ctx.helper.success({beans: users})
  }

  async marryLike(user) {
    let marryLike;
    if (user.marry_like && user.marry_like.length > 0) {
      marryLike = JSON.parse(param);
      if (user.vip) {
        if (marryLike.educationLevel.length == 0) {
          marryLike.educationLevel = '1,2,3,4,5';
        }
        if (marryLike.constellation.length == 0) {
          marryLike.constellation = '白羊座,金牛座,双子座,巨蟹座,狮子座,处女座,天秤座,天蝎座,射手座,摩羯座,水瓶座,双鱼座';
        }
      } else {
        //不是VIP，只有性别，年龄
        marryLike.minHeight = 0;
        marryLike.maxHeight = 230;
        marryLike.educationLevel = '1,2,3,4,5';
        marryLike.constellation = '白羊座,金牛座,双子座,巨蟹座,狮子座,处女座,天秤座,天蝎座,射手座,摩羯座,水瓶座,双鱼座';
      }
    } else {
      marryLike = {
        sex: '1,2',
        minAge: '0',
        maxAge: '50',
        minHeight: '0',
        maxHeight: '230',
        educationLevel: '1,2,3,4,5',
        constellation: '白羊座,金牛座,双子座,巨蟹座,狮子座,处女座,天秤座,天蝎座,射手座,摩羯座,水瓶座,双鱼座',
      }
    }
    return marryLike;
  }

  /**
   * 个人资料
   */
  async show() {
    const userId = await this.userId();
    const Op = this.app.Sequelize.Op;
    const user = await this.app.model.User.findOne({
      where: {
        id: userId
      },
      include: [
        {
          model: this.app.model.UserImage,
          as: 'images',
          attributes: ['id', 'image', 'index'],
        }, 
        {
          model: this.app.model.UserQuestion,
          as: 'questions',
          attributes: ['id', 'content', 'create_time', 'question_id', 'title'],
        }
      ],
      order: [
        ['images', 'index', 'asc'],
        ['questions', 'create_time', 'desc']
      ],
    });
    if (!user) {
      this.ctx.helper.commonErr('用户不存在');
    }
    const now = moment().format("YYYY-MM-DD");
    if (moment(user.expire_time) < moment(now)) {
      user.vip = false;
    }
    // const themes = await this.service.theme.findByUserId(userId);
    this.ctx.helper.success({ 
      bean: {
        user,
        // themes
      } 
    });
  }

  /**
   * 编辑
   */
  async edit() {
    const { ctx, service } = this;
    const data = ctx.request.body;
    const userId = await this.userId();
    const res =  service.user.update(userId, data);
    ctx.helper.success();
  }

  // 获取七牛token
  async qiniuToken() {
    const { ctx, service } = this;
    const uploadToken = await service.userImage.getToken();
    ctx.helper.success({bean: { qiniuToken: uploadToken }}, '获取七牛token成功！');
    
  }

  // 上传七牛云链接
  async addUserImage() {
    const { ctx, service, app } = this;
    const errors = app.validator.validate(addUserImage, ctx.request.body);
    errors && ctx.helper.commonErr('参数错误', { beans: errors });
    const id = ctx.helper.decodeJwt(ctx);
    const data = ctx.request.body;
    const res = await service.userImage.addUserImage({
      user_id: id,
      ...data
    });
    ctx.helper.success({bean: res}, '图片添加成功!');
  }

  
}

module.exports = UserController;
